<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @row-update="rowUpdate"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-document-copy" size="small" @click.stop="handleCopy(row)">复制</el-button>
        <el-button type="text" icon="el-icon-edit" size="small" @click.stop="handleDesign(row)">设计</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="rowDel(row)">删除</el-button>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="addBtn">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">删 除 </el-button>
      </template>
    </avue-crud>

    <el-dialog
      :title="designerDialog.title"
      :visible.sync="designerDialog.visible"
      :close-on-click-modal="false"
      :fullscreen="true"
      custom-class="designerDialog"
      append-to-body
      @close="closeDesignerDialog"
    >
      <form-designer v-if="designerDialog.visible" ref="designer" @addTemplateSuccess="addTemplateSuccess"></form-designer>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, remove, add, update, copy } from '@/api/designer/apaasList';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

import formDesigner from './index.vue';
export default {
  name: 'ApaasModelMange',
  components: {
    userTableConfig,
    formDesigner
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'APAAS_MANGE',
      designerDialog: {
        visible: false,
        title: '新增'
      },
      form: {},
      query: {},
      timer: new Date().getTime(),
      addDialog: false,
      editDialog: false,
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        searchLabelWidth: 120,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        editBtn: true,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        labelWidth: 120,
        menuWidth: 300,
        column: [
          {
            label: '检验模板名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请选择检验模板名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验模板编码',
            prop: 'code',
            disabled: true,
            search: true
          },
          {
            label: '检验模板类型',
            prop: 'type',
            type: 'select',
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=QC',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '创建时间',
            prop: 'createTime',
            disabled: true
          },
          {
            label: '最后更改时间',
            prop: 'updateTime',
            disabled: true
          }
        ]
      },
      data: [],
      properties: {}, //表单
      title: '',
      showSelectSectionDialog: false,
      selectWorkSectionForm: {
        workSectionId: ''
      },
      workSectionList: [],
      rowId: '',
      rules: {
        workSectionId: [{ required: true, message: '请选择所属工段', trigger: 'blur' }]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.stationManage_add, false),
        delBtn: this.vaildData(this.permission.stationManage_delete, false),
        editBtn: this.vaildData(this.permission.stationManage_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    closeDesignerDialog() {
      this.designerDialog.visible = false;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    reset() {
      this.addDialog = false;
      this.$refs.addProperties.resetForm();
    },
    addBtn() {
      this.designerDialog.visible = true;
      this.designerDialog.title = '新增模板';
      setTimeout(() => {
        this.$refs.designer.initDesigner();
      }, 100);
    },
    handleCopy(row) {
      copy(row.id).then((res) => {
        this.$message.success('复制成功!');
        this.onLoad(this.page);
      });
    },
    handleDesign(row) {
      this.designerDialog.visible = true;
      this.designerDialog.title = '设计模板';
      setTimeout(() => {
        this.$refs.designer.initDesigner(row.id);
      }, 100);
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud && this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.descs = 'create_time';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    rowUpdate(form, index, done, loading) {
      update(form).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    addTemplateSuccess() {
      this.closeDesignerDialog();
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .designerDialog {
  .el-dialog__body {
    padding: 0;
  }
}
</style>
